#!/bin/bash
set -eu
THIS="$(readlink -f "$0")"
THISDIR="$(dirname "${THIS}")"
SUT="$(dirname "${THISDIR}")/makeself.sh"

testSuidDoesntGetBroken() {
    # Create a directory with a file on it
    local archive_dir="$(mktemp -dt archive_dir.XXXXXX)"
    (
        cd "${archive_dir}"
        touch deployedfile
    )
    # Create the self extracting that should extract deployedfile
    local file_name="$(mktemp -t file_name.XXXXXX)"
    "${SUT}" --target "${archive_dir}" "${archive_dir}" "${file_name}" "suid test"
    assertEquals $? 0
    # Target directory now has another file with sudo permissions
    # This will get broken because of chown -R
    (
        cd "${archive_dir}"
        touch suidfile.bin
        chmod +xs suidfile.bin
    )
    permissionsBefore=$(stat -c %A "${archive_dir}"/suidfile.bin)
    # We extract deployedfile, in hopes that it will not reset suid bit
    # from suidfile.bin
    "${file_name}"
    assertEquals $? 0
    permissionsAfter=$(stat -c %A "${archive_dir}"/suidfile.bin)
    # And we check that permissions match
    assertEquals "${permissionsBefore}" "${permissionsAfter}"
    rm -rf "${archive_dir}" "${file_name}"
}

# Load and run shUnit2.
source "./shunit2/shunit2"

